package com.yycx.module.bus.provider.handler.haiying.tasktodo.settle;

import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.yycx.bpm.provider.common.CommentTypeEnum;
import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.module.export.DictDataVo;
import com.yycx.common.base.module.export.ExportField;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.mybatis.interceptor.ExportInterceptor;
import com.yycx.common.mybatis.interceptor.PageInterceptor;
import com.yycx.common.mybatis.model.PageParams;
import com.yycx.common.mybatis.query.CriteriaQuery;
import com.yycx.common.security.OpenHelper;
import com.yycx.common.utils.ApiAssert;
import com.yycx.common.utils.ConvertUtils;
import com.yycx.module.admin.client.entity.BaseUser;
import com.yycx.module.admin.provider.service.BaseRoleService;
import com.yycx.module.admin.provider.service.BaseUserService;
import com.yycx.module.bus.client.entity.*;
import com.yycx.module.bus.client.entity.hy.BusHyorderInoviceDetails;
import com.yycx.module.bus.client.entity.hy.HyOrder;
import com.yycx.module.bus.provider.service.*;
import com.yycx.module.bus.provider.service.hy.BusHyorderReturnService;
import org.flowable.engine.TaskService;
import org.flowable.engine.task.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 结算审批支付单详情
 *
 * @author zyf
 */
@Component
public class HySettlePayDetailsPageListHandler implements PageInterceptor<BusHyorderInoviceDetails>, ExportInterceptor {


    @Autowired
    private BusHyorderReturnService hyorderReturnService;

    @Autowired
    private BusSalemanService salemanService;
    @Autowired
    private BusDeptService deptService;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private TaskService taskService;
    @Autowired
    private BaseUserService userService;
    @Autowired
    private BaseRoleService roleService;
    @Autowired
    private BusPaymentService paymentService;

    @Override
    public void prepare(CriteriaQuery<BusHyorderInoviceDetails> cq, PageParams pageParams, EntityMap params) {
        cq.clear();
        Long paymentId = params.getLong("paymentId");
        ApiAssert.isNotEmpty("参数异常", paymentId);
        BusPayment payment=paymentService.getById(paymentId);
        String beginDate = params.get("beginDate");
        String endDate = params.get("endDate");
        String orderNo = params.get("orderNo");
        String saleManName = params.get("saleManName");
        cq.select(BusHyorderInoviceDetails.class, "*");
        cq.addSelect(HyOrder.class, "orderId", "outOrderNo", "orderNo", "sendDate", "businessCode", "sendType", "customBondType", "saleManName");
        cq.select(BusCustom.class, "customName", "settleType");
        //业务员
        cq.like("ho.saleManName", saleManName);
        //发货单号
        if (FlymeUtils.isNotEmpty(orderNo)) {
            cq.and(e -> e.like("ho.orderNo", orderNo).or().like("ho.outOrderNo", orderNo));
        }
        //购货方
        cq.like(BusCustom.class, "customName");
        //发货日期
        cq.ge(FlymeUtils.isNotEmpty(beginDate), "ho.sendDate", beginDate);
        cq.le(FlymeUtils.isNotEmpty(endDate), "ho.sendDate", endDate);
        cq.eq(true, "bhid.payId", paymentId);
        cq.eq(HyOrder.class, "deptId");
        cq.createJoin(BusCustom.class);
        cq.createJoin(HyOrder.class);
        params.put("settleType",payment.getSettleType());
        params.put("paymentNo",payment.getPaymentNo());

    }

    @Override
    public List<EntityMap> complete(CriteriaQuery<BusHyorderInoviceDetails> cq, List<EntityMap> result, EntityMap extra) {
        for (EntityMap entityMap : result) {
            Long settleInvoiceId = entityMap.getLong("settleInvoiceId");
            Long orderDetailsReturnId = entityMap.getLong("orderDetailsReturnId");
            EntityMap orderDetailsInfo = hyorderReturnService.selectOrderDetailsInfo(orderDetailsReturnId);
            entityMap.putAll(orderDetailsInfo);
            Long saleManId=entityMap.getLong("saleManId");
            if(FlymeUtils.isNotEmpty(saleManId)){
                BusSaleman saleman=salemanService.getById(saleManId);
                entityMap.put("saleManName",saleman.getSaleManName());
                entityMap.put("saleManBusinessNo",saleman.getSaleManBusinessNo());
            }
            Long deptId=entityMap.getLong("deptId");
            if(FlymeUtils.isNotEmpty(deptId)){
                BusDept dept=deptService.getById(deptId);
                entityMap.put("deptName",dept.getDeptName());
            }
            entityMap.put("disabled", false);
            if (FlymeUtils.isNotEmpty(settleInvoiceId)) {
                entityMap.put("disabled", true);
            }
        }
        return PageInterceptor.super.complete(cq, result, extra);
    }

    @Override
    public void initExcelExportEntity(ExportField exportField, List list) {
        Object key = exportField.getKey();
        if (key.equals("deptType")) {
            List<DictDataVo> dictDataVos = new ArrayList<>();
            DictDataVo dictDataVo = new DictDataVo();
            dictDataVo.setLabel("自营");
            dictDataVo.setValue("ZY");
            DictDataVo dictDataVo2 = new DictDataVo();
            dictDataVo2.setLabel("招商");
            dictDataVo2.setValue("ZS");
            dictDataVos.add(dictDataVo);
            dictDataVos.add(dictDataVo2);
            exportField.setDictData(dictDataVos);
            exportField.setReplace();
        }
        if (key.equals("sendType")) {
            List<DictDataVo> dictDataVos = new ArrayList<>();
            DictDataVo dictDataVo = new DictDataVo();
            dictDataVo.setLabel("现款");
            dictDataVo.setValue(1);
            DictDataVo dictDataVo2 = new DictDataVo();
            dictDataVo2.setLabel("预付款");
            dictDataVo2.setValue(2);
            DictDataVo dictDataVo3 = new DictDataVo();
            dictDataVo3.setLabel("资保金");
            dictDataVo3.setValue(3);
            DictDataVo dictDataVo4 = new DictDataVo();
            dictDataVo4.setLabel("资信");
            dictDataVo4.setValue(4);
            dictDataVos.add(dictDataVo);
            dictDataVos.add(dictDataVo2);
            dictDataVos.add(dictDataVo3);
            dictDataVos.add(dictDataVo4);
            exportField.setDictData(dictDataVos);
            exportField.setReplace();
        }
    }
    @Override
    public TemplateExportParams initTemplateExportParams(Map params) {
        Integer settleType = MapUtil.getInt(params, "settleType",1);
        TemplateExportParams templateExportParams = new TemplateExportParams("excel/结算申请明细" + settleType + ".xlsx", true);
        return templateExportParams;
    }

    @Override
    public void initExportData(Map dataMap, List list,CriteriaQuery cq) {
        dataMap.put("nickName", OpenHelper.getNickName());
        dataMap.put("applyDate", DateUtil.format(DateUtil.date(), "yyyy-MM-dd"));
        Long companyId = OpenHelper.getCompanyId();
        String paymentNo= cq.getParams("paymentNo");
        dataMap.put("paymentNo",paymentNo);
        if(companyId.equals(5L)){
            dataMap.put("companyName","丹博瑞");
        }
        if(companyId.equals(1018L)){
            dataMap.put("companyName","赤壁医药");
        }
        String processInstanceId = request.getParameter("processInstanceId");
        //查询审批人
        if (FlymeUtils.isNotEmpty(processInstanceId)) {
            List<Comment> commentsList = taskService.getProcessInstanceComments(processInstanceId, CommentTypeEnum.WC.toString());
            if (FlymeUtils.isNotEmpty(list)) {
                commentsList = commentsList.stream().filter(ConvertUtils.distinctByKey(Comment::getUserId)).collect(Collectors.toList());
                for (Comment comment : commentsList) {
                    String userId = comment.getUserId();
                    BaseUser baseUser = userService.getUserById(Long.parseLong(userId));
                    List<String> roleCodes = roleService.selectRoleCodesByUserId(baseUser.getUserId());
                    if (roleCodes.contains("ROLE_CW_JSY")) {
                        dataMap.put("nickName_cw_jsy", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_CW_FHY")) {
                        dataMap.put("nickName_cw_fhy", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_SW_SCZZ")) {
                        dataMap.put("nickName_sw_sczz", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_SW_FHY")) {
                        dataMap.put("nickName_sw_fhy", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_CW_JSBX")) {
                        dataMap.put("nickName_jsbz", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_CW_CWBZ")) {
                        dataMap.put("nickName_cwbz", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_CW_ZJ")) {
                        dataMap.put("nickName_cwzj", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_FLP_ZJL")) {
                        dataMap.put("nickName_zjl", baseUser.getNickName());
                    }
                }
            }
        }
    }
}
